import moment from "moment";

import { getRequest, postRequest, putRequest, delRequest } from "@/api/public"; //调用接口

import { reqLoading, req } from "@/api/req"; //调用接口
// 当前时间
const current = moment().format("YYYY-MM-DD HH:mm:ss").valueOf();
// 今天
const todayStart = moment()
  .startOf("days")
  .format("YYYY-MM-DD HH:mm:ss")
  .valueOf();
const todayEnd = moment().endOf("days").format("YYYY-MM-DD HH:mm:ss").valueOf();
// 昨天
const yesterdayS = moment(moment().add(-1, "days").startOf("day").valueOf())
  .format("YYYY-MM-DD HH:mm:ss")
  .valueOf();
const yesterdayE = moment(moment().add(-1, "days").endOf("day").valueOf())
  .format("YYYY-MM-DD HH:mm:ss")
  .valueOf();
// 本周
const weekS = moment()
  .weekday(1)
  .startOf("day")
  .format("YYYY-MM-DD HH:mm:ss")
  .valueOf();
// 上周
const lastWeekS = moment(
  moment()
    .week(moment().week() - 1)
    .startOf("week")
    .valueOf()
)
  .add(1, "day")
  .format("YYYY-MM-DD HH:mm:ss");
const lastWeekE = moment(
  moment()
    .week(moment().week() - 1)
    .endOf("week")
    .valueOf()
)
  .add(1, "day")
  .format("YYYY-MM-DD HH:mm:ss");
// 本月
const monthS = moment()
  .month(moment().month())
  .startOf("month")
  .format("YYYY-MM-DD HH:mm:ss")
  .valueOf();
// 上月
const lastMonthS = moment(
  moment()
    .month(moment().month() - 1)
    .startOf("month")
    .valueOf()
).format("YYYY-MM-DD HH:mm:ss");
const lastMonthE = moment(
  moment()
    .month(moment().month() - 1)
    .endOf("month")
    .valueOf()
).format("YYYY-MM-DD HH:mm:ss");
// 本季度
const quarterS = moment(
  moment().quarter(moment().quarter()).startOf("quarter").valueOf()
).format("YYYY-MM-DD HH:mm:ss");
const quarterE = moment(
  moment().quarter(moment().quarter()).endOf("quarter").valueOf()
).format("YYYY-MM-DD HH:mm:ss");
// 上季度
const lastQuarterS = moment(
  moment()
    .quarter(moment().quarter() - 1)
    .startOf("quarter")
    .valueOf()
).format("YYYY-MM-DD HH:mm:ss");
const lastQuarterE = moment(
  moment()
    .quarter(moment().quarter() - 1)
    .endOf("quarter")
    .valueOf()
).format("YYYY-MM-DD HH:mm:ss");
// 本年
const yearS = moment(
  moment().year(moment().year()).startOf("year").valueOf()
).format("YYYY-MM-DD HH:mm:ss");
const yearE = moment(
  moment().year(moment().year()).endOf("year").valueOf()
).format("YYYY-MM-DD HH:mm:ss");

export default {
  data() {
    return {
      title: "",
      version: "4.0.0.1",
      //搜索模型
      filterModel: {},
      //表单模型
      formModel: {},
      //数据校验规则
      formRules: {},
      isNew: false,
      isEdit: false,

      // fetchData 默认传的参数
      pageRequest: {
        page: 1,
        pageSize: 100,
      },

      // 分页默认参数
      page: {
        total: null, // 总条数
        sizes: [100, 200, 300, 500],
      },

      //  table数据
      tableData: [],

      //表格默认高度
      tableHeight: 300,

      //vxe-table s
      gridOptions: {
        border: true,
        size: "mini",
        resizable: true,
        showOverflow: true,
        // height: 600,
        align: "left",
        toolbarConfig: {
          slots: {
            // 自定义工具栏模板
            buttons: "toolbar_buttons",
          },
        },
      },

      // vxe-table工具栏
      tableToolbar: {
        export: true,
        print: true,
        custom: true,
        zoom: true, //全屏
        //按钮
        slots: {
          buttons: "toolbar_buttons",
        },
      },
      // vxe-table e

      // 日期和时间
      todayStart,
      todayEnd,
      yesterdayS,
      yesterdayE,
      weekS,
      lastWeekS,
      lastWeekE,
      monthS,
      lastMonthS,
      lastMonthE,
      quarterS,
      quarterE,
      lastQuarterS,
      lastQuarterE,
      yearS,
      yearE,
      current,

      // 日期和时间范围
      filterdate: [todayStart, todayEnd],
      // 日期和时间范围 快捷选项
      pickerOptions: {
        shortcuts: [
          {
            text: "今天",
            onClick(picker) {
              picker.$emit("pick", [todayStart, todayEnd]);
            },
          },
          {
            text: "昨天",
            onClick(picker) {
              picker.$emit("pick", [yesterdayS, yesterdayE]);
            },
          },
          {
            text: "本周",
            onClick(picker) {
              picker.$emit("pick", [weekS, todayEnd]);
            },
          },
          {
            text: "上周",
            onClick(picker) {
              picker.$emit("pick", [lastWeekS, lastWeekE]);
            },
          },
          {
            text: "本月",
            onClick(picker) {
              picker.$emit("pick", [monthS, todayEnd]);
            },
          },
          {
            text: "昨 至 今",
            onClick(picker) {
              picker.$emit("pick", [yesterdayS, todayEnd]);
            },
          },
        ],
      },
    };
  },
  mounted() {
    /**
     * 监听窗口大小设置表格高度
     */
    this.$nextTick(function () {
      if (this.$refs.vxeTable != undefined) {
        this.tableHeight =
          window.innerHeight -
          this.$refs.vxeTable.$el.getBoundingClientRect().top -
          80;
        var that = this;
        window.onresize = function () {
          that.tableHeight =
            window.innerHeight -
            that.$refs.vxeTable.$el.getBoundingClientRect().top -
            80;
        };
      }
    });
  },
  async created() {
    // console.log(1,this.path);
  },

  methods: {
    /**
     * 格式化日期时间
     * @param {*} dateTimeStr 传入的时间格式是YYYY-MM-DD HH:mm:ss
     */
    formatDateTime(dateTimeStr) {
      //   console.log(4, dateTimeStr);
      const date = new Date(dateTimeStr);
      return `${date.getFullYear()}-${("0" + (date.getMonth() + 1)).slice(
        -2
      )}-${("0" + date.getDate()).slice(-2)} ${("0" + date.getHours()).slice(
        -2
      )}:${("0" + date.getMinutes()).slice(-2)}:${(
        "0" + date.getSeconds()
      ).slice(-2)}`;
    },

    /**
     * 判断日期时间是否过期（超过7天）
     * @param {*} dateTimeStr 传入的时间格式是YYYY-MM-DD HH:mm:ss
     */
    isDateExpired(dateTimeStr) {
      //   console.log(3, dateTimeStr);
      const currentDate = new Date();
      const inputDate = new Date(dateTimeStr);

      // 7天的时间差（单位：毫秒）
      const sevenDays = 7 * 24 * 60 * 60 * 1000;

      // 如果时间差大于7天，则返回 true
      return currentDate - inputDate > sevenDays;
    },
    /**
     * 字符串转驼峰
     */
    toCamel(str) {
      return str.replace(/([^_])(?:_+([^_]))/g, function ($0, $1, $2) {
        return $1 + $2.toUpperCase();
      });
    },

    /**
     * 睡眠
     */
    sleep(numberMillis) {
      var now = new Date();
      var exitTime = now.getTime() + numberMillis;
      while (true) {
        now = new Date();
        if (now.getTime() > exitTime) {
          return;
        }
      }
    },

    /**
     * 数组对象转一维数组
     */
    toArrar(list, field) {
      let params = [];
      list.forEach((v) => {
        params.push(v[field]);
      });
      return params;
    },

    /**
     * 获取数据
     */
    async fetchData() {
      let _url = this.requestURL.listApi[0];
      let _method = this.requestURL.listApi[1];
      let params = Object.assign({}, this.pageRequest, this.filterModel);
      let url = await this.toGet(_url, params);
      let res = await getRequest(url);
      if (res.status_code == 200) {
        this.tableData = res.data;
        this.page.total = Number(res.meta.total);
      } else {
        this.resMessage("出错了", "接口数据错误", "error");
      }
    },

    /**
     * 请求接口
     */
    request(method, url, data, isLoading) {
      let res = [];
      if (method == "get") {
        if (isLoading) res = reqLoading(method, url);
        else res = req(method, url);
        return res;
      }
      if (method == "post") {
        if (isLoading) res = reqLoading(method, url, data);
        else res = req(method, url, data);
        return res;
      }
      if (method == "put") {
        if (isLoading) res = reqLoading(method, url, data);
        else res = req(method, url, data);
        return res;
      }
      if (method == "delete") {
        if (isLoading) res = reqLoading(method, url, data);
        else res = req(method, url, data);
        return res;
      }
    },

    /**
     * URL拼接
     * 如sysUser/cancelFreeze?userName=111
     */
    urlJoin(params) {
      let urlStr = "?";
      for (let val in params) {
        if (params[val] && params[val] != null) {
          urlStr += val + "=" + params[val] + "&";
        }
      }
      if (urlStr[urlStr.length - 1] === "&") {
        urlStr = urlStr.slice(0, urlStr.length - 1);
      }
      return urlStr;
    },

    /**
     * 清除搜索查询条件
     */
    clearFilter() {
      // console.log();
      let { filterModel } = require(`@/model/${this.path}/${this.module}`);
      this.filterModel = new filterModel();
      this.fetchData();
    },

    /**
     * 分页
     */
    // 每页数改变时
    async sizeChange(val) {
      this.pageRequest.page = 1; //每页数改变时，第几页设置为第一页
      this.pageRequest.pageSize = Number(val);
      await this.fetchData();
    },
    // 点第几页
    async currentChangeHandle(val) {
      this.pageRequest.page = val;
      await this.fetchData();
    },

    /**
     * 页面搜索
     */
    searchHandle() {
      this.$refs.search.search();
    },
    searchSub() {
      this.pageRequest.page = 1;
      this.fetchData();
    },

    /**
     * GET URL拼接
     */
    async toGet(url, params) {
      let searchStr = "?";
      for (let val in params) {
        if (params[val] && params[val] != null) {
          searchStr += val + "=" + params[val] + "&";
        }
      }
      if (searchStr[searchStr.length - 1] === "&") {
        searchStr = searchStr.slice(0, searchStr.length - 1);
      }
      return url + searchStr;
    },

    /**
     * 弹出框提示消息
     * success/warning/info/error
     */
    resMessage(title, msg, type) {
      this.$alert(msg, "提示", {
        title: title,
        confirmButtonText: "确定",
        type: type,
      });
    },

    /**
     * 提示消息
     */
    resMes(msg, type, time) {
      this.$message({
        message: msg,
        type: type, // success/warning/info/error
        duration: time,
      });
    },
  },
};
